package ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.WindowConstants;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;

import net.Client;
import net.handler.AccepHandler;
import net.im.IMMessagePacket;
import ui.module.PrivateChatModule;

public class MainFrame extends JFrame implements Observer {
	private JLabel ipStartLabel;
	private JLabel nickLabel;
	private JLabel localIPLabel;
	private JLabel timeLabel;
	private JLabel countLabel;

	private JTextField updateNickTField;
	private JTextField ipStartTField;
	private JTextField ipEndTField;

	private JButton aboutBt;
	private JButton sendMessageBt;
	private JButton updateNickBt;
	private JButton fontSizeBt;
	private JButton exitBt;

	private JSlider fontSizeSlider;

	private JToggleButton searchUserButton;
	private JProgressBar progressBar;

	private DefaultTableModel onlineUsersModel;
	private DefaultTableModel searchUsersModel;

	private Vector<String> searchUsersVector;
	private Vector<String> onlineUsersVector;

	private JTextArea sendMessageArea;
	private JTextArea displayArea;

	private Thread searchThread = null;

	private JTable searchUsersTable;
	private JTable onlineUsersTable;

	public static Client client;

	private StringBuffer displayBuffer = new StringBuffer();

	public static String userName;
	public static String userIP;
	public static String times;
	private String ipStartCache;

	private HashMap<String, String> usersMap = new HashMap<String, String>();
	private HashMap<String, String> onLineMap = new HashMap<String, String>();

	public static JTabbedPane jtp;

	private JPopupMenu popupMenu;

	private int MapSize = 0;
	private int[] ipStart = null;

	public MainFrame() {
		this.setTitle("LanChat (局域网聊天)");
		this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

		Toolkit tool = Toolkit.getDefaultToolkit();// 创建系统该默认组件工具包
		Dimension d = tool.getScreenSize();// 获取屏幕尺寸，赋给一个二维坐标对象
		this.setSize(d.width - d.width / 4, d.height - d.height / 4);// 设置窗体大小
		// 让主窗体在屏幕中间显示
		this.setLocation((d.width - getWidth()) / 2, (d.height - getHeight()) / 2);

		uiInit();
		addActionListener();
		getLocalIP();

		client = new Client();
		new Thread(client).start();

		Timer timer = new Timer();
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				client.send(new IMMessagePacket(userIP, userName, "状态", "1"));
			}
		};
		timer.schedule(task, 0, 2000);

		AccepHandler.getAccepHandler().addObserver(this);
	}

	private void getLocalIP() {
		StringBuffer subIP = new StringBuffer();
		try {
			String[] split = InetAddress.getLocalHost().getHostAddress().split("\\.");
			for (int i = 0; i < split.length - 1; i++) {
				subIP.append(split[i]).append(".");
			}
			ipStartTField.setText(subIP.toString() + "1");
			ipEndTField.setText(subIP.append("255").toString());
		} catch (UnknownHostException e) {
			ipStartTField.setText("192.168.1.1");
			ipEndTField.setText("192.168.1.255");
			e.printStackTrace();
		}
	}

	private void uiInit() {
		JSplitPane SplitPane1 = new JSplitPane();
		SplitPane1.setOneTouchExpandable(true);// 让分割线显示出箭头
		SplitPane1.setContinuousLayout(true);// 操作箭头，重绘图形
		SplitPane1.setLeftComponent(chitChatZone());
		SplitPane1.setRightComponent(searchUsers());

		JSplitPane SplitPane2 = new JSplitPane();
		SplitPane2.setOneTouchExpandable(true);// 让分割线显示出箭头
		SplitPane2.setContinuousLayout(true);// 操作箭头，重绘图形
		SplitPane2.setLeftComponent(onlineUsers());
		SplitPane2.setRightComponent(SplitPane1);

		SplitPane1.addComponentListener(new ComponentAdapter() {
			public void componentResized(ComponentEvent e) {

				SplitPane1.setDividerLocation(0.65);
			}
		});
		SplitPane2.addComponentListener(new ComponentAdapter() {
			public void componentResized(ComponentEvent e) {

				SplitPane2.setDividerLocation(0.25);
			}
		});

		this.setLayout(new BorderLayout());

		JToolBar topToolBar = new JToolBar("顶部工具栏");
		topToolBar.addSeparator(new Dimension(15, 0));
		try {
			userName = InetAddress.getLocalHost().getHostName();
			userIP = InetAddress.getLocalHost().getHostAddress();
			nickLabel = new JLabel("本机名称：" + userName);
			localIPLabel = new JLabel("本机IP：" + userIP);

			topToolBar.add(nickLabel);
			topToolBar.addSeparator(new Dimension(15, 0));
			topToolBar.add(localIPLabel);
			topToolBar.addSeparator(new Dimension(15, 0));

		} catch (UnknownHostException e1) {
			nickLabel.setText("当前昵称：获取失败！");
			localIPLabel.setText("本机IP：获取失败！");
			e1.printStackTrace();
		}
		Timer timer = new Timer();
		TimerTask task = new TimerTask() {
			SimpleDateFormat from = new SimpleDateFormat(" yyyy - MM - dd HH : mm : ss ");

			@Override
			public void run() {
				Date date = new Date();
				times = from.format(date);
				timeLabel.setText("现在时间：" + times);
			}
		};
		timer.schedule(task, 0, 1000);
		timeLabel = new JLabel();
		topToolBar.add(timeLabel);
		topToolBar.addSeparator(new Dimension(15, 0));
		aboutBt = new JButton("开发人员");
		topToolBar.add(aboutBt);
		topToolBar.addSeparator(new Dimension(15, 0));
		topToolBar.add(new JLabel("修改昵称："));
		topToolBar.addSeparator(new Dimension(15, 0));
		updateNickTField = new JTextField(userName);
		updateNickTField.setEnabled(false);
		topToolBar.add(updateNickTField);
		topToolBar.addSeparator(new Dimension(15, 0));
		updateNickBt = new JButton("更改");
		topToolBar.add(updateNickBt);
		topToolBar.addSeparator(new Dimension(15, 0));
		exitBt = new JButton("退出程序");
		topToolBar.add(exitBt);
		topToolBar.addSeparator(new Dimension(15, 0));

		topToolBar.setFloatable(false);

		this.add(topToolBar, BorderLayout.NORTH);
		this.add(SplitPane2, BorderLayout.CENTER);
	}

	private JPanel searchUsers() {
		JPanel searchUserPanel = new JPanel(new BorderLayout());

		JPanel searchPanel = new JPanel();
		searchPanel.setLayout(new BorderLayout());
		searchPanel.setBorder(new TitledBorder("搜索网络设备"));
		JPanel gridPanel = new JPanel();
		GridLayout gridLayout_1 = new GridLayout(0, 1);
		gridLayout_1.setVgap(5);
		gridPanel.setLayout(gridLayout_1);
		String[] columnNames = new String[] { "设备名称", "IP地址" };
		Object[][] tableValues = null;
		searchUsersModel = new DefaultTableModel(tableValues, columnNames) {
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		searchUsersTable = new JTable(searchUsersModel);
		JTableHeader tableHeader = searchUsersTable.getTableHeader();

		DefaultTableCellRenderer dtcrModel = (DefaultTableCellRenderer) tableHeader.getDefaultRenderer();
		dtcrModel.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
		searchUsersTable.setTableHeader(tableHeader);
		JScrollPane scrollPane = new JScrollPane(searchUsersTable);
		scrollPane.setDoubleBuffered(true);
		progressBar = new JProgressBar();
		progressBar.setStringPainted(true);// 进度条中可以展示文字
		progressBar.setString("搜索状态：停止");
		searchUserButton = new JToggleButton();
		searchUserButton.setText("搜索局域网在线设备");
		gridPanel.add(progressBar);
		gridPanel.add(searchUserButton);
		searchPanel.add(scrollPane, BorderLayout.CENTER);
		searchPanel.add(gridPanel, BorderLayout.SOUTH);

		searchUserPanel.add(searchPanel, BorderLayout.CENTER);

		JPanel ipPanel = new JPanel();
		ipPanel.setBorder(new TitledBorder("IPv4搜索范围"));
		GridLayout gridLayout_2 = new GridLayout(0, 1);
		gridLayout_2.setVgap(5);
		ipPanel.setLayout(gridLayout_2);
		JPanel ipStartPanel = new JPanel();
		ipStartPanel.setLayout(new BoxLayout(ipStartPanel, BoxLayout.X_AXIS));
		ipPanel.add(ipStartPanel);
		ipStartLabel = new JLabel("起始IP：");
		ipStartPanel.add(ipStartLabel);
		ipStartTField = new JTextField();
		ipStartPanel.add(ipStartTField);
		JPanel ipEndPanel = new JPanel();
		ipEndPanel.setLayout(new BoxLayout(ipEndPanel, BoxLayout.X_AXIS));
		ipPanel.add(ipEndPanel);
		ipEndPanel.add(new JLabel("终止IP："));
		ipEndTField = new JTextField();
		ipEndPanel.add(ipEndTField);

		searchUserPanel.add(ipPanel, BorderLayout.SOUTH);

		return searchUserPanel;
	}

	private JPanel onlineUsers() {
		JPanel onlineUsersPanel = new JPanel(new BorderLayout());
		onlineUsersPanel.setLayout(new BorderLayout());
		onlineUsersPanel.setBorder(new TitledBorder("在线用户"));
		String[] columnNames = new String[] { "用户昵称", "用户IP" };
		Object[][] tableValues = null;
		onlineUsersModel = new DefaultTableModel(tableValues, columnNames) {
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		onlineUsersTable = new JTable(onlineUsersModel);
		JTableHeader tableHeader = onlineUsersTable.getTableHeader();
		// 设置不可以重排
		// tableHeader.setReorderingAllowed(false);
		DefaultTableCellRenderer dtcrModel = (DefaultTableCellRenderer) tableHeader.getDefaultRenderer();
		dtcrModel.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
		onlineUsersTable.setTableHeader(tableHeader);
		JScrollPane scrollPane = new JScrollPane(onlineUsersTable);
		scrollPane.setDoubleBuffered(true);
		onlineUsersPanel.add(scrollPane, BorderLayout.CENTER);
		JPanel onlineUsersCountPanel = new JPanel();
		onlineUsersCountPanel.setLayout(new BoxLayout(onlineUsersCountPanel, BoxLayout.X_AXIS));
		onlineUsersCountPanel.setBorder(new TitledBorder("在线人数"));
		onlineUsersCountPanel.add(new JLabel("总人数为："));
		countLabel = new JLabel();
		countLabel.setForeground(Color.BLUE);
		onlineUsersCountPanel.add(countLabel);
		onlineUsersPanel.add(onlineUsersCountPanel, BorderLayout.SOUTH);

		return onlineUsersPanel;
	}

	private JPanel chitChatZone() {
		JPanel jp = new JPanel();
		jp.setLayout(new BorderLayout());
		jtp = new JTabbedPane(JTabbedPane.SCROLL_TAB_LAYOUT);
		jtp.addTab("公共聊天室", null, publicChatModule(), "你可以与在线用户聊天啦！");
		jp.add(jtp, BorderLayout.CENTER);
		return jp;
	}

	private JPanel publicChatModule() {
		displayArea = new JTextArea();
		displayArea.setEditable(false);
		JScrollPane daScrollPane = new JScrollPane(displayArea);
		JToolBar toolBar = new JToolBar("聊天工具栏");
		toolBar.setFloatable(false);
		toolBar.addSeparator(new Dimension(15, 0));
		toolBar.add(new JLabel("设置字体大小："));
		toolBar.addSeparator(new Dimension(15, 0));
		fontSizeSlider = new JSlider();
		fontSizeSlider.setMaximum(40);
		fontSizeSlider.setValue(14);
		displayArea.setFont(new Font("微软雅黑", Font.BOLD, fontSizeSlider.getValue()));
		fontSizeSlider.setEnabled(false);
		toolBar.add(fontSizeSlider);
		toolBar.addSeparator(new Dimension(15, 0));
		fontSizeBt = new JButton("更改");
		toolBar.add(fontSizeBt);
		toolBar.addSeparator(new Dimension(15, 0));
		JPanel borderPanel = new JPanel();
		borderPanel.setLayout(new BorderLayout());
		borderPanel.add(toolBar, BorderLayout.NORTH);
		sendMessageArea = new JTextArea();
		JScrollPane smaScrollPane = new JScrollPane(sendMessageArea);
		borderPanel.add(smaScrollPane, BorderLayout.CENTER);
		JPanel flowPanel = new JPanel(new FlowLayout(2, 5, 10));
		sendMessageBt = new JButton("发送消息");
		flowPanel.add(sendMessageBt);
		borderPanel.add(flowPanel, BorderLayout.SOUTH);

		JSplitPane SplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, daScrollPane, borderPanel);
		SplitPane.setOneTouchExpandable(true);
		SplitPane.setContinuousLayout(true);
		SplitPane.addComponentListener(new ComponentAdapter() {
			public void componentResized(ComponentEvent e) {

				SplitPane.setDividerLocation(0.65);
			}
		});

		JPanel chatModulePanel = new JPanel();
		chatModulePanel.setLayout(new BorderLayout());
		chatModulePanel.add(SplitPane, BorderLayout.CENTER);

		return chatModulePanel;
	}

	private void createPopupMenu(String ip, String name) {
		popupMenu = new JPopupMenu();
		JMenuItem sendMenItem = new JMenuItem();
		sendMenItem.setText("发送私信 ");
		sendMenItem.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				if (jtp.indexOfTab(name) == -1)
					jtp.addTab(name, null, new PrivateChatModule().uiInit(ip, name, ""), "你可以与在线用户私聊啦！");
			}
		});
		popupMenu.add(sendMenItem);
	}

	private void addActionListener() {
		onlineUsersTable.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getButton() == MouseEvent.BUTTON3) {
					try {
						int row = onlineUsersTable.getSelectedRow();
						String name = onlineUsersTable.getValueAt(row, 0).toString();
						String ip = onlineUsersTable.getValueAt(row, 1).toString();
						createPopupMenu(ip, name);
						popupMenu.show(onlineUsersTable, e.getX(), e.getY());
					} catch (Exception exception) {
						JOptionPane.showMessageDialog(null, "请选择除自己的某一行。", "温馨提示", JOptionPane.INFORMATION_MESSAGE);
					}
				}
			}
		});

		fontSizeBt.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (fontSizeBt.getText().equals("更改")) {
					fontSizeBt.setText("确定");
					fontSizeSlider.setEnabled(true);
				} else {
					displayArea.setFont(new Font("微软雅黑", Font.BOLD, fontSizeSlider.getValue()));
					fontSizeBt.setText("更改");
					fontSizeSlider.setEnabled(false);
				}
			}
		});

		updateNickBt.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (updateNickBt.getText().equals("更改")) {
					updateNickBt.setText("确定");
					updateNickTField.setEnabled(true);
				} else {
					userName = updateNickTField.getText();
					updateNickBt.setText("更改");
					updateNickTField.setEnabled(false);
				}
			}
		});

		exitBt.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				client.send(new IMMessagePacket(userIP, userName, "状态", "0"));
				System.exit(0);
			}
		});

		searchUserButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (searchUserButton.getText() == "搜索局域网在线设备") {
					searchUserButton.setText("取消搜索");
				} else {
					searchUserButton.setText("搜索局域网在线设备");
				}
				if (searchThread == null) {
					searchThread = new Thread(new Runnable() {

						@Override
						public void run() {
							while (searchUsersModel.getRowCount() != 0) {
								searchUsersModel.removeRow(0);
							}
							String ipPattern = new String("\\d{1,4}\\.\\d{1,4}\\.\\d{1,4}\\.\\d{1,4}");
							String[] ipStartGroup, ipEndGroup;
							if (ipStartTField.getText().matches(ipPattern)
									&& ipEndTField.getText().matches(ipPattern)) {
								ipStartGroup = ipStartTField.getText().split("\\.");
								ipEndGroup = ipEndTField.getText().split("\\.");
								for (int i = 0; i < 4; i++) {
									if (i == 0) {
										if (!((Integer.parseInt(ipStartGroup[0]) > 0
												&& Integer.parseInt(ipStartGroup[0]) <= 255)
												&& (Integer.parseInt(ipEndGroup[0]) > 0
														&& Integer.parseInt(ipEndGroup[0]) <= 255))) {
											JOptionPane.showMessageDialog(null, "iPv4数值不正确", "警示框",
													JOptionPane.WARNING_MESSAGE);
											initSearchState();
											return;
										}
									} else if (!((Integer.parseInt(ipStartGroup[i]) >= 0
											&& Integer.parseInt(ipStartGroup[i]) <= 255)
											&& (Integer.parseInt(ipEndGroup[i]) >= 0
													&& Integer.parseInt(ipEndGroup[i]) <= 255))) {
										JOptionPane.showMessageDialog(null, "iPv4数值不正确", "警示框",
												JOptionPane.WARNING_MESSAGE);
										initSearchState();
										return;
									}
								}
							} else {
								JOptionPane.showMessageDialog(null, "iPv4格式不正确", "警示框", JOptionPane.WARNING_MESSAGE);
								initSearchState();
								return;
							}

							ipStartTField.setEnabled(false);
							ipEndTField.setEnabled(false);
							progressBar.setIndeterminate(true);// 使用不确定进度条
							ipStartLabel.setText("现在IP：");
							ipStartCache = ipStartTField.getText();

							try {
								ipStart = new int[] { Integer.valueOf(ipStartGroup[0]),
										Integer.valueOf(ipStartGroup[1]), Integer.valueOf(ipStartGroup[2]),
										Integer.valueOf(ipStartGroup[3]) };
								int[] ipEnd = new int[] { Integer.valueOf(ipEndGroup[0]),
										Integer.valueOf(ipEndGroup[1]), Integer.valueOf(ipEndGroup[2]),
										Integer.valueOf(ipEndGroup[3]) };
								if (judgeSize(ipStart, ipEnd) == 0) {
									if (InetAddress
											.getByName(
													ipStart[0] + "." + ipStart[1] + "." + ipStart[2] + "." + ipStart[3])
											.isReachable(500)) {
										addUser(ipStart[0] + "." + ipStart[1] + "." + ipStart[2] + "." + ipStart[3]);
									}
									return;
								} else if (judgeSize(ipStart, ipEnd) == 1) {
									while (true) {
										if (!searchUserButton.getText().equals("取消搜索")) {// 如果搜索用户按钮是非选中状态
											return;
										} else if ((ipStart[0] != ipEnd[0]) || (ipStart[1] != ipEnd[1])
												|| (ipStart[2] != ipEnd[2]) || (ipStart[3] != ipEnd[3])) {
											addUser(ipStart[0] + "." + ipStart[1] + "." + ipStart[2] + "."
													+ ipStart[3]);
											if (ipStart[3] < 255) {
												ipStart[3]++;
											} else if (ipStart[2] < 255) {
												ipStart[3] = 0;
												ipStart[2]++;
											} else if (ipStart[1] < 255) {
												ipStart[2] = 0;
												ipStart[1]++;
											} else if (ipStart[0] < 255) {
												ipStart[1] = 0;
												ipStart[0]++;
											}
										} else {
											addUser(ipStart[0] + "." + ipStart[1] + "." + ipStart[2] + "."
													+ ipStart[3]);
											return;
										}
									}
								} else if (judgeSize(ipStart, ipEnd) == -1) {
									while (true) {
										if (!searchUserButton.getText().equals("取消搜索")) {// 如果搜索用户按钮是非选中状态
											return;// 结束方法
										} else if ((ipStart[0] != ipEnd[0]) || (ipStart[1] != ipEnd[1])
												|| (ipStart[2] != ipEnd[2]) || (ipStart[3] != ipEnd[3])) {
											addUser(ipStart[0] + "." + ipStart[1] + "." + ipStart[2] + "."
													+ ipStart[3]);
											if (ipStart[3] > 0) {
												ipStart[3]--;
											} else if (ipStart[2] >= 0) {
												ipStart[3] = 255;
												ipStart[2]--;
											} else if (ipStart[1] >= 0) {
												ipStart[2] = 255;
												ipStart[1]--;
											} else if (ipStart[0] >= 0) {
												ipStart[1] = 255;
												ipStart[0]--;
											}
										} else {
											addUser(ipStart[0] + "." + ipStart[1] + "." + ipStart[2] + "."
													+ ipStart[3]);
											return;
										}
									}
								}
							} catch (Exception e) {
								e.printStackTrace();
							} finally {
								ipStartLabel.setText("起始IP：");
								ipStartTField.setText(ipStartCache);
								initSearchState();
							}
						}
					});
					searchThread.start();
				}
			}
		});

		aboutBt.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				new AboutUsFrame().setVisible(true);
			}
		});

		sendMessageBt.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (!sendMessageArea.getText().equals("")) {
					client.send(new IMMessagePacket(userIP, userName, "消息", sendMessageArea.getText()));
					sendMessageArea.setText("");
				}
			}
		});

		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosed(WindowEvent e) {
				client.send(new IMMessagePacket(userIP, userName, "状态", "0"));
				System.exit(0);
			}
		});
	}

	private void initSearchState() {
		searchThread = null;
		searchUserButton.setText("搜索局域网在线设备");
		searchUserButton.setSelected(false);
		progressBar.setIndeterminate(false);// 不使用不确定进度条
		ipStartTField.setEnabled(true);
		ipEndTField.setEnabled(true);
	}

	private Integer judgeSize(int[] ipStart, int[] ipEnd) {
		Integer judgeSize = null;
		if (ipStart[0] != ipEnd[0]) {
			if (ipStart[0] > ipEnd[0]) {
				judgeSize = -1;
			} else {
				judgeSize = 1;
			}
		} else if (ipStart[1] != ipEnd[1]) {
			if (ipStart[1] > ipEnd[1]) {
				judgeSize = -1;
			} else {
				judgeSize = 1;
			}
		} else if (ipStart[2] != ipEnd[2]) {
			if (ipStart[2] > ipEnd[2]) {
				judgeSize = -1;
			} else {
				judgeSize = 1;
			}
		} else if (ipStart[3] != ipEnd[3]) {
			if (ipStart[3] > ipEnd[3]) {
				judgeSize = -1;
			} else {
				judgeSize = 1;
			}
		} else {
			judgeSize = 0;
		}

		return judgeSize;
	}

	private void addUser(String ip) {
		searchUsersVector = new Vector<>();
		ipStartTField.setText(String.valueOf(ipStart[0] + "." + ipStart[1] + "." + ipStart[2] + "." + ipStart[3]));
		try {
			if (InetAddress.getByName(ip).isReachable(1000)) {
				if (InetAddress.getByName(ip).getHostName().equals(ip)) {
					searchUsersVector.add("未知");
				} else {
					searchUsersVector.add(InetAddress.getByName(ip).getHostName());
				}
				searchUsersVector.add(ip);
				searchUsersModel.addRow(searchUsersVector);
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void addOnlines() {
		if (usersMap.size() != MapSize) {
			while (onlineUsersModel.getRowCount() != 0) {
				onlineUsersModel.removeRow(0);
			}
			for (String s : usersMap.keySet()) {
				onlineUsersVector = new Vector<>();
				onlineUsersVector.add(usersMap.get(s));
				onlineUsersVector.add(s);
				onlineUsersModel.addRow(onlineUsersVector);
			}
			MapSize = usersMap.size();
			countLabel.setText(usersMap.size() + " 人");
		}
	}

	@Override
	public void update(Observable o, Object arg) {
		if (o instanceof AccepHandler) {
			AccepHandler pdp = (AccepHandler) o;
			IMMessagePacket ms = pdp.getData();
			if (ms.getDataType().equals("状态")) {
				if (ms.getData().equals("1")) {
					if (userIP.equals(ms.getUserIP())) {
						usersMap.put(ms.getUserIP(), "自己");
					} else {
						if (usersMap.get(ms.getUserIP()) == null) {
							Timer timer = new Timer();
							TimerTask task = new TimerTask() {
								String onLineString = ms.getUserIP();

								@Override
								public void run() {
									if ("在线".equals(onLineMap.get(onLineString))) {
										onLineMap.put(ms.getUserIP(), "判断中");
									} else if ("判断中".equals(onLineMap.get(onLineString))) {
										onLineMap.remove(onLineString);
										usersMap.remove(onLineString);
										timer.cancel();
									}
								}
							};
							timer.schedule(task, 0, 2000);
						}
						onLineMap.put(ms.getUserIP(), "在线");
						usersMap.put(ms.getUserIP(), ms.getUserName());
					}
				} else {
					onLineMap.remove(ms.getUserIP());
					usersMap.remove(ms.getUserIP());
				}
				addOnlines();
			} else if (ms.getDataType().equals("消息")) {
				displayBuffer
						.append(" >> " + ms.getUserName() + " " + times + " :" + "\n  " + ms.getData().trim() + "\n");
				displayArea.setText(displayBuffer.toString());
			} else if (ms.getDataType().equals("私聊")) {
				if (jtp.indexOfTab(ms.getUserName()) == -1 && !ms.getUserName().equals(userName)) {
					jtp.addTab(ms.getUserName(), null,
							new PrivateChatModule().uiInit(ms.getUserIP(), ms.getUserName(), ms.getData()),
							"你可以与在线用户私聊啦！");
				}
			}
		}
	}
}
